<template>
  <div>
    <div class="login-form_wrapper">
      <el-form
        :model="loginForm"
        :rules="rules"
        ref="from"
        @keyup.enter.native="submitForm('from')"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="submitForm('from')"
            >登录</el-button
          >
          <el-button @click="resetForm('from')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/login'
import Cookie from 'js-cookie'
export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      loading: false,
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.login()
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    login() {
      this.loading = true
      login(this.loginForm)
        .then((res) => {
          if (res.errorCode === '0000') {
            //返回token与按钮权限permSign
            Cookie.set('token', res.data.token)
            console.log(res, 'res.token')
            Cookie.set(
              'user',
              `${this.loginForm.username},${this.loginForm.password}`
            )

            this.$message.success('登录成功！')
            this.$router.push('/')
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>

<style lang="scss">
.login-form_wrapper {
  width: 500px;
  margin: 100px auto;
  padding: 20px;
}
</style>
this.loading
